/*
 * Created on Feb 25, 2008 Copyright (c) Sybase, Inc. 2008 All rights reserved.
 */

package edu.cmu.cs.webapp.ioms.utils;

import java.util.HashMap;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import edu.cmu.cs.webapp.ioms.IOMSActivator;

/**
 * Image helper class to handle images used in SAP connection profile
 * 
 * @author tqiu
 */
public class IOMSImageHelper {
	private static IOMSImageHelper _instance;
	private HashMap<String, ImageDescriptor> fImageDescRegistry;

	private IOMSImageHelper() {
		// Default empty constructor
	}

	public static synchronized IOMSImageHelper getInstance() {
		if (_instance == null) {
			_instance = new IOMSImageHelper();
		}
		return _instance;
	}

	/**
	 * gets the image through the given image path
	 * 
	 * @param imagePath
	 * @return
	 */
	public Image getImage(String imagePath) {
		Image image = getImageRegistry().get(imagePath);
		if (image == null) {
			// create an image
			image = createImage(imagePath);
		}
		return image;
	}

	/**
	 * creates the image instance from the given path and add it to the diamg
	 * 
	 * @param imagePath
	 * @return
	 */
	private Image createImage(String imagePath) {
		ImageDescriptor desc = getImageDescriptor(imagePath);
		Image image = null;

		if (desc != null) {
			image = desc.createImage();
			// don add the missing image descriptor image to the image
			if (!desc.equals(ImageDescriptor.getMissingImageDescriptor())) {
				getImageRegistry().put(imagePath, image);
			}
		}
		return image;
	}

	/**
	 * 
	 * @param imagePath
	 * @return
	 */
	public ImageDescriptor getImageDescriptor(String imagePath) {
		ImageDescriptor imageDescriptor = null;
		Object o = getImageDescriptorRegistry().get(imagePath);
		if (o == null) {
			// create a descriptor
			imageDescriptor = createImageDescriptor(imagePath);
		} else {
			imageDescriptor = (ImageDescriptor) o;
		}
		return imageDescriptor;
	}

	private ImageDescriptor createImageDescriptor(String imagePath) {
		ImageDescriptor descriptor = AbstractUIPlugin
				.imageDescriptorFromPlugin(IOMSActivator.PLUGIN_ID, imagePath);
		if (descriptor != null) {
			getImageDescriptorRegistry().put(imagePath, descriptor);
		} else {
			descriptor = ImageDescriptor.getMissingImageDescriptor();
		}

		return descriptor;
	}

	/**
	 * 
	 * @return
	 */
	private HashMap<String, ImageDescriptor> getImageDescriptorRegistry() {
		if (this.fImageDescRegistry == null) {
			this.fImageDescRegistry = new HashMap<String, ImageDescriptor>();
		}
		return this.fImageDescRegistry;
	}

	/**
	 * Returns the image registry for this plugin.
	 * 
	 * @return ImageRegistry - image registry for this plugin
	 */
	private ImageRegistry getImageRegistry() {
		return JFaceResources.getImageRegistry();
	}

}
